<template>
  <div>
    <el-dialog title="充值" :model-value="visible" width="600px" @close="close">
      <el-form class="form_wrap" :model="formData" label-width="80px" :rules="rules" label-position="top" ref="form">
        <el-form-item label="账号" prop="account">
          <el-input v-model="formData.account"></el-input>
        </el-form-item>

        <el-form-item label="金额" prop="money">
          <el-input v-model.number="formData.money"></el-input>
        </el-form-item>
      </el-form>

      <div class="confirm_btn">
        <el-button type="danger" @click="handleConfirm">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { reactive, ref, toRefs, nextTick, watchEffect } from 'vue';
import { addPayOrder } from '@/api/recharge';

export default {
  name: 'PayDialog',
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    item: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },

  setup(props, context) {
    const form = ref(null);
    let item;
    watchEffect(() => {
      item = props.item;
    });
    const state = reactive({
      formData: {
        account: '',
        money: '',
      },
      rules: {
        account: [{ required: true, message: '请输入充值账号', trigger: 'blur' }],
        money: [
          { required: true, message: '请输入充值金额', trigger: 'blur' },
          {
            pattern: /\d+/g,
            message: '请输入整数数字',
            trigger: 'blur',
          },
        ],
      },
    });

    const handleConfirm = async () => {
      nextTick(() => {
        form.value.validate(async valid => {
          if (valid) {
            const { account, money } = state.formData;
            await addPayOrder({ account, money, details: item.name });
          }
        });
      });
    };

    const close = () => {
      context.emit('close');
    };

    return {
      ...toRefs(state),
      handleConfirm,
      close,
      form,
      props,
    };
  },
};
</script>

<style lang="scss" scoped>
.confirm_btn {
  text-align: center;
}
</style>
